package com.df.library.net;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

import java.util.LinkedList;
import java.util.List;

/**
 * tcp 服务
 */
public class TcpServer extends CommonServer {

    public List<ChannelHandler> customHandlers = new LinkedList<>();

    public TcpServer(){}
    public TcpServer(String name, int port,List<ChannelHandler> customHandlers){
        super();
        setName(name);
        addListenPort(port);
        if(customHandlers!=null){
            customHandlers.addAll(customHandlers);
        }
        setChannelInitializer(new TcpServer.TcpChannelInitializer(this.customHandlers));
    }
    public TcpServer(String name, int port,List<ChannelHandler> customHandlers, ChannelHandler bossChannelHandler){
        this(name,port,customHandlers);
        setBossChannelHandler(bossChannelHandler);
    }

    private static class TcpChannelInitializer extends ChannelInitializer<SocketChannel>{
        private List<ChannelHandler> customHandlers;
        public TcpChannelInitializer(List<ChannelHandler> customHandlers){
            this.customHandlers = customHandlers;
        }
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline pipeline = socketChannel.pipeline();
            if(customHandlers!=null && !customHandlers.isEmpty()){
                for (ChannelHandler customHandler : customHandlers) {
                    pipeline.addLast(customHandler);
                }
            }
        }
    }

}
